<template>
	<el-dialog
		:destroy-on-close="true"
		title="代理场馆费率编辑"
		:visible.sync="dialogFormVisible"
		align="center"
		width="750px"
		@close="hide"
	>
		<el-form ref="formSub" :model="dialogForm" label-width="auto">
			<el-form-item
				v-if="title === `${$t('common.add')}`"
				:label="`${$t('merchant.merchant_select')}:`"
				:rules="[
					{
						required: true,
						message: $t('merchant.merchant_placeholder'),
						trigger: 'change'
					}
				]"
				prop="merchantId"
			>
				<el-select
					v-model.trim="dialogForm.merchantId"
					:placeholder="$t('common.please_choose')"
					autocomplete="off"
					style="width: 340px"
				>
					<el-option
						v-for="item in merchartList"
						:key="item.id"
						:disabled="item.disabled"
						:label="item.merchantName"
						:value="item.id"
					></el-option>
				</el-select>
			</el-form-item>
		</el-form>
		<div class="flex-right">
			商户名称 德信
		</div>
		<div class="flex-right">
			<el-button
				:loading="btnLoading"
				type="success"
				@click="addList"
				:disabled="orgData.length >= 6"
			>
				{{ $t('common.add') }}
			</el-button>
			<el-button
				:loading="btnLoading"
				type="warning"
				@click="subAddOrEdit"
			>
				{{ $t('common.save') }}
			</el-button>
		</div>
		<el-table :data="orgData" border>
			<el-table-column
				:label="$t('merchant.insert_venue')"
				align="center"
				:close="(currentEditIndex = false)"
				prop="venueName"
			>
				<template slot-scope="scope">
					<el-form
						:ref="`tabVenueRef${scope.$index}`"
						:model="scope.row"
					>
						<el-form-item
							:rules="[
								{
									required: true,
									message: $t(
										'merchant.merchant_venue_insert_placeholder'
									),
									trigger: 'change'
								}
							]"
							prop="venueCode"
						>
							<el-select
								v-model="scope.row.venueCode"
								:disabled="!scope.row.isSelect"
								:placeholder="$t('common.please_choose')"
								clearable
							>
								<el-option
									v-for="item in bwVenueList"
									:key="item.venueCode"
									:disabled="item.disabled"
									:label="item[getKey('venueName')]"
									:value="item.venueCode"
								></el-option>
							</el-select>
						</el-form-item>
					</el-form>
				</template>
			</el-table-column>
			<el-table-column
				:label="`${$t('merchant.agent_venue_pre')}%`"
				align="center"
				prop="venueFeeRate"
			>
				<template slot-scope="scope">
					<el-form
						:ref="`tabRef${scope.$index}`"
						:model="scope.row"
						:rules="formRule"
					>
						<el-form-item
							prop="venueFeeRate"
							style="margin-bottom: 0;"
						>
							<span style="display: flex;align-items: center;">
								<label
									for=""
									v-if="scope.row.venueCode === 'DZ'"
									style="width: 100px;"
								>
									俱乐部：
								</label>
								<el-input
									v-model.trim="scope.row.venueFeeRate"
									:disabled="!scope.row.isSelect"
									:placeholder="$t('common.please_enter')"
									clearable
									maxlength="5"
									oninput="value = value.replace(/[^\d.]/g, '')"
									show-word-limit
									@blur="formatThreeDecimalFull($event)"
								></el-input>
							</span>
							<span
								style="display: flex;align-items: center;"
								v-if="scope.row.venueCode === 'DZ'"
							>
								<label for="" style="width: 100px;">
									保险：
								</label>
								<el-input
									v-model.trim="scope.row.insureFeeRate"
									:disabled="!scope.row.isSelect"
									placeholder="保险"
									clearable
									maxlength="5"
									oninput="value = value.replace(/[^\d.]/g, '')"
									show-word-limit
									@blur="formatThreeDecimalFull($event)"
								></el-input>
							</span>
						</el-form-item>
					</el-form>
				</template>
			</el-table-column>
			<el-table-column :label="$t('common.actions')" align="center">
				<template slot-scope="scope">
					<div
						v-if="
							currentEditIndex &&
								!scope.row.isSelect &&
								currentEditIndex !== scope.$index
						"
					>
						/
					</div>
					<div v-else>
						<el-button
							size="medium"
							type="text"
							@click="editList(scope.row, scope.$index)"
						>
							{{
								scope.row.isSelect
									? $t('common.sure')
									: $t('common.edit')
							}}
						</el-button>
						<el-button
							size="medium"
							style="color: #F56C6C"
							type="text"
							v-if="!scope.row.isSelect"
							@click="deleteList(scope.row, scope.$index)"
						>
							{{ $t('common.delete') }}
						</el-button>
						<el-button
							size="medium"
							style="color: #F56C6C"
							type="text"
							v-else
							@click="cancelList(scope.row, scope.$index)"
						>
							取消
						</el-button>
					</div>
				</template>
			</el-table-column>
		</el-table>
	</el-dialog>
</template>

<script>
import list from '@/mixins/list'
import i18n from '@/locales'
import {
	addMerchantVenueApi,
	updateMerchantVenueApi
} from '@/api/merchant/merchant-config/venue-config'

export default {
	name: 'EditAndAdd',
	mixins: [list],
	props: {
		title: {
			type: String,
			default: i18n.t('common.add')
		},
		venueList: {
			type: Array,
			default: () => {
				return []
			}
		},
		merchartList: {
			type: Array,
			default: () => {
				return []
			}
		}
	},
	data() {
		const vaildVenueFeeRate = (rule, value, callback) => {
			if (!value) {
				callback(
					new Error(
						`${this.$t('merchant.agent_venue_pre_placeholder')}`
					)
				)
			} else if (value >= 100 || value < 0) {
				callback(new Error(`${this.$t('merchant.input_less_100')}`))
			} else {
				callback()
			}
		}
		return {
			dialogForm: {},
			dialogFormVisible: false,
			tableData: [],
			orgData: [],
			btnLoading: false,
			formRule: {
				venueFeeRate: [
					{
						required: true,
						validator: vaildVenueFeeRate,
						trigger: 'blur'
					}
				]
			},
			currentEditIndex: false
		}
	},
	computed: {
		bwVenueList() {
			const venueList = JSON.parse(JSON.stringify(this.venueList))
			if (this.dialogFormVisible) {
				this.orgData.map((item) => {
					venueList.map((venue) => {
						if (item.venueCode === venue.venueCode) {
							venue.disabled = true
						}
					})
				})
				return venueList
			}
			return venueList
		}
	},
	watch: {
		dialogFormVisible: {
			deep: true,
			handler: function(newV, oldV) {
				if (newV && this.title !== `${this.$t('common.add')}`) {
					this.tableData.map((item) => {
						const e = {
							isSelect: false,
							venueCode: item.venueCode,
							venueFeeRate: this.formatThreeDecimalFull(
								item.venueFeeRate
							),
							venueName: item.venueName
						}
						if (item.venueCode === 'DZ') {
							e.insureFeeRate = this.formatThreeDecimalFull(
								item.insureFeeRate
							)
						}
						this.orgData.push(e)
					})
				} else {
					this.dialogForm = {}
					this.orgData = []
				}
			}
		}
	},
	methods: {
		formatThreeDecimalFull(num) {
			if (num === '') {
				return ''
			}
			const result = Number(
				(num || 0).toString().match(/^\d+(?:\.\d{0,3})?/)
			)
			let s_x = result.toString()
			let pos_decimal = s_x.indexOf('.')
			if (pos_decimal < 0) {
				pos_decimal = s_x.length
				s_x += '.'
			}
			while (s_x.length <= pos_decimal + 3) {
				s_x += '0'
			}
			return s_x
		},
		subAddOrEdit() {
			const arr = []
			this.orgData.map((item, index) => {
				arr.push(this.$refs[`tabVenueRef${index}`].validate())
				arr.push(this.$refs[`tabRef${index}`].validate())
			})
			arr.push(this.$refs['formSub'].validate())
			Promise.all(arr).then(async (valids) => {
				if (valids.filter((el) => !el).length === 0) {
					const select = this.orgData.some((item) => {
						return item.isSelect
					})
					if (!this.orgData.length) {
						this.$message({
							message: `${this.$t(
								'merchant.add_venue_placeholder'
							)}`,
							type: 'error'
						})
						return
					}
					if (select) {
						this.$message({
							message: `${this.$t('merchant.please_sure')}`,
							type: 'error'
						})
						return
					}
					const list = []
					this.orgData.map((item) => {
						const e = {
							venueFeeRate: this.formatThreeDecimalFull(
								item.venueFeeRate
							),
							venueCode: item.venueCode
						}
						if (item.venueCode === 'DZ') {
							e.insureFeeRate = this.formatThreeDecimalFull(
								item.insureFeeRate
							)
						}
						list.push(e)
					})
					list.map((item) => {
						item.venueFeeRate =
							(item.venueFeeRate * 10000 * 0.01) / 10000
						if (item.venueCode === 'DZ') {
							item.insureFeeRate =
								(item.insureFeeRate * 10000 * 0.01) / 10000
						}
					})
					const params = {
						merchantId: this.dialogForm.merchantId,
						list: list
					}
					try {
						this.btnLoading = true
						this.title === this.$t('common.add')
							? await addMerchantVenueApi(params)
							: await updateMerchantVenueApi(params)

						this.$message({
							message: `${this.$t('common.action_success')}`,
							type: 'success'
						})
						this.btnLoading = false
						this.hide()
						this.$emit('loadData')
						this.$refs.formSub.resetFields()
					} catch (e) {
						this.btnLoading = false
						this.$refs.formSub.resetFields()
					}
				}
			})
		},
		hide() {
			this.$refs.formSub.resetFields()
			this.dialogFormVisible = false
		},
		formatVenueFeeRate(e) {
			e.target.value = this.formatThreeDecimalFull(e.target.value)
		},
		editList(row, index) {
			this.currentEditIndex = !this.currentEditIndex
				? String(index)
				: false
			const arr = []
			arr.push(this.$refs[`tabVenueRef${index}`].validate())
			arr.push(this.$refs[`tabRef${index}`].validate())
			Promise.all(arr).then((valids) => {
				if (valids) {
					row.isSelect = !row.isSelect
				}
			})
		},
		deleteList(row, index) {
			this.orgData.splice(index, 1)
		},
		cancelList(row, index) {
			this.orgData = []
			this.tableData.map((item) => {
				const e = {
					isSelect: false,
					venueCode: item.venueCode,
					venueFeeRate: this.formatThreeDecimalFull(
						item.venueFeeRate
					),
					venueName: item.venueName
				}
				if (item.venueCode === 'DZ') {
					e.insureFeeRate = this.formatThreeDecimalFull(
						item.insureFeeRate
					)
				}
				this.orgData.push(e)
			})
			this.$forceUpdate()
		},
		addList() {
			this.orgData.push({
				isSelect: true,
				venueCode: '',
				venueFeeRate: '',
				venueName: ''
			})
		}
	}
}
</script>

<style scoped lang="scss">
.flex-right {
	margin: 10px 0;
	display: flex;
	justify-content: flex-start;
	align-items: center;
}
</style>
